/**
 * 绘制 map 主文件，mapTool 主体
 */
import mapMix from '../mixins/mapMix';
import gameBody from './gameBody';
import pageLabel from './pageLabel';
import { Stage, Layer } from '../render/index';
import { IMapClassParameter } from '../../types/mapClass';

export default class MapEditor extends mapMix {
    /**
     * konva canvas对象
     */
    public konva: any;
    /**
     * canvas 主画布
     */
    public canvas: any;
    /**
     * 背景
     */
    public gameComp: gameBody | undefined;
    /**
     * 页面label
     */
    public pageLabel: pageLabel | undefined;
    /**
     * 信息块数组
     */
    public inForMations: [] = [];

    constructor(data: IMapClassParameter) {
        super({
            id: 'tetris',
        });

        this.mapConst.setEditorFN(this);
        this.mapConst.setGameSizeFS(data.width, data.height).then(() => {
            Stage({
                container: data.domId,
                width: data.width,
                height: data.height,
            }).then(Stage => {
                this.konva = Stage;
                this.gameComp = new gameBody();
                this.loadCanvasFN().then(() => {
                    console.error('加载完成');
                    this.pageLabel = new pageLabel();
                    window.requestAnimationFrame(() => this.stepGameFS());
                });
            });
        });
    }

    /**
     * 主画布
     */
    private loadCanvasFN() {
        return new Promise<void>(resolve => {
            Layer({ // 主画布
                id: `${this.id}_game`,
                x: 0,
                y: 0,
            }).then(Layer => {
                this.canvas = Layer;
                this.konva.add(this.canvas);
                resolve();
            });
        });
    }

    /**
     * 游戏循环
     */
    public stepGameFS(){
        if(this.pageLabel){
            this.pageLabel.setPageLabelFN();
        }
        this.gameComp && this.gameComp.loadGamePreviewIconRectFN();
        this.mapConst.gamePlay();
        window.requestAnimationFrame(() => this.stepGameFS());
    }
}
